const { app, BrowserWindow, ipcMain, dialog } = require('electron');
const path = require('path');
const fs = require('fs');

let mainWindow;

function createWindow() {
    mainWindow = new BrowserWindow({
        width: 1200,
        height: 800,
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false
        }
    });

    mainWindow.loadFile('index.html');

    mainWindow.on('closed', () => {
        mainWindow = null;
    });
}

app.on('ready', createWindow);

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit();
    }
});

app.on('activate', () => {
    if (mainWindow === null) {
        createWindow();
    }
});

ipcMain.on('save-image', (event, { dataURL, savePath, scanData }) => {
    const base64Data = dataURL.replace(/^data:image\/png;base64,/, '');
    const fileName = `${scanData}_${Date.now()}.png`;
    const filePath = path.join(savePath, fileName);
    fs.writeFile(filePath, base64Data, 'base64', err => {
        if (err) {
            console.error('Error saving image:', err);
            event.sender.send('image-save-error', err.message);
        } else {
            console.log('Image saved:', filePath);
            event.sender.send('image-saved', filePath);
        }
    });
});
